package com.vpen.iot.client.handler;

import com.vpen.iot.server.handler.IotServerChannelInitializer;
import com.vpen.iot.server.handler.IotServerHandler;
import com.vpen.iot.server.message.v2.Message;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author Vpen
 * @date 2023/7/8 11:41
 */
@Slf4j
@Component
public class ClientInitializer  extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) {
        // 从channel种获取pipeline
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new LoggingHandler(LogLevel.INFO));
        // out
        pipeline.addLast(new DelimiterEncoder());
        //protobuf的编码器 和上面对对应
        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
        //protobuf的编码器
        pipeline.addLast(new ProtobufEncoder());


        // in
        //添加protobuf解码器

        pipeline.addLast("delimiter", new DelimiterBasedFrameDecoder(1024, IotServerChannelInitializer.getDelimiter()));
        pipeline.addLast(new ProtobufVarint32FrameDecoder());
        //添加protobuf对应类解码器
//        pipeline.addLast(new ProtobufDecoder(User.UserBase.getDefaultInstance()));
        pipeline.addLast(new ProtobufDecoder(Message.MessageBase.getDefaultInstance()));

        // 添加自己的业务处理器
        pipeline.addLast("serverHandler", new IotServerHandler());
    }
}
